package com.cwx.web.WechatItem;

import com.alibaba.fastjson.JSONObject;
import com.cwx.config.WechatConfiguration;
import com.cwx.dao.entity.Member;
import com.cwx.service.MemberService;
import com.cwx.utils.HttpUtils;
import com.cwx.utils.Tool;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ligang on 2017/9/23.
 */
@Controller
@RequestMapping("/wechat")
@Log
public class WechatIndexController {

    @Autowired
    private MemberService memberService;

    @RequestMapping("/loginPage")
    public String loginPage(){
        return "/html/wechat/enter";
    }
    @RequestMapping("/registerPage")
    public String registerPage(){
        return "/html/wechat/register";
    }
    @RequestMapping("/toMain")
    public String toMain(){
        return "/html/wechat/index";
    }

    @RequestMapping("/retrievePwd")
    public String retrievePwd(){
        return "/html/wechat/changePas";
    }
    @RequestMapping("toRealName")
    public String toRealName(){
        return "/html/wechat/realName";
    }
    @RequestMapping("toBill")
    public String toBill(){
        return "/html/wechat/bill";
    }
    @RequestMapping("toBankInfo")
    public String toBankInfo() {
        return "/html/wechat/bankInfo";
    }
    @RequestMapping("/index")
    public String index(){
        return "/html/wechat/enter";
    }
    @RequestMapping("/toWechatApply")
    public String toWechatApply(Model model){
        model.addAttribute("type","wechat");
        return "/html/baseInfo";
    }
    @RequestMapping("/toSmallOrder")
    public String toSmallOrder() {
        return "/html/wechat/smallOrder";
    }
    @RequestMapping("/toSmallContacts")
    public String toSmallContacts(){
        return "/html/wechat/smallContacts";
    }
    @RequestMapping("/toSamllBase")
    public String toSamllBase(){
        return "/html/wechat/samllBase";
    }
    @RequestMapping("/totb")
    public String totb(){
        return "/html/wechat/tb";
    }
    @RequestMapping("/tojdxx")
    public String tojdxx(){
        return "/html/wechat/jdorxx";
    }

    @RequestMapping("/toBind")
    public String toBind(HttpSession session){
        Map<String,String> params = new HashMap<>();
        try {
            params.put("appid",WechatConfiguration.APP_ID);
            params.put("redirect_uri", URLEncoder.encode(WechatConfiguration.BIND_REDIRECT_URI,"utf-8"));
            params.put("response_type","code");
            params.put("scope","snsapi_base");
        } catch (IOException e) {
            log.info("系统错误：" + e.getMessage());
        }
        return "redirect:" + WechatConfiguration.GET_CODE_URL + "?" + Tool.mapToPostData(params) + "#wechat_redirect";
    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        Map<String,String> params = new HashMap<>();
        try {
            params.put("appid",WechatConfiguration.APP_ID);
            params.put("redirect_uri", URLEncoder.encode(WechatConfiguration.LOGIN_REDIRECT_URI,"utf-8"));
            params.put("response_type","code");
            params.put("scope","snsapi_base");
        } catch (IOException e) {
            log.info("系统错误：" + e.getMessage());
        }
        return "redirect:" + WechatConfiguration.GET_CODE_URL + "?" + Tool.mapToPostData(params) + "#wechat_redirect";
    }
    @RequestMapping("/bind")
    public String bind(String code,String state,HttpSession session){
        Map<String,String> params = new HashMap<>();
        params.put("appid",WechatConfiguration.APP_ID);
        params.put("secret",WechatConfiguration.APP_SECRET);
        params.put("code",code);
        params.put("grant_type","authorization_code");
        try {
            String resultStr = HttpUtils.get(WechatConfiguration.GET_ACCESS_TOKEN_URL,params,"gbk");
            JSONObject result = JSONObject.parseObject(resultStr);
            if (result.containsKey("errcode")){
                log.info("授权失败:" + resultStr);
            }else {
                String openid = result.getString("openid");
                Member member = new Member();
                member.setOpenid(openid);
                memberService.save(member);
                session.setAttribute("member",member);
            }
        } catch (IOException e) {
            log.info("系统错误：" + e.getMessage());
        }
        return "redirect:/wechat/toSmallOrder";
    }

    @RequestMapping("/login")
    public String login(String code,String state,HttpSession session){
        Map<String,String> params = new HashMap<>();
        params.put("appid",WechatConfiguration.APP_ID);
        params.put("secret",WechatConfiguration.APP_SECRET);
        params.put("code",code);
        params.put("grant_type","authorization_code");
        try {
            String resultStr = HttpUtils.get(WechatConfiguration.GET_ACCESS_TOKEN_URL,params,"gbk");
            JSONObject result = JSONObject.parseObject(resultStr);
            if (result.containsKey("errcode")){
                log.info("授权失败:" + resultStr);
            }else {
                String openid = result.getString("openid");
                Member member = memberService.findByOpenid(openid);
                if (member == null){
                    return "redirect:/wechat/toBind";//提示去绑定
                }
                session.setAttribute("member",member);
            }
        } catch (IOException e) {
            log.info("系统错误：" + e.getMessage());
        }
        return "redirect:/wechat/toSmallOrder";
    }
}
